/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
const PENDING = "pending"
const FULFILED = "fulfiled"
const REJECTED = "rejected"
class MyPromise {
    constructor(executor) {
        executor(this.resolve, this.reject)
    }
    status = PENDING // 状态标志位
        // 成功之后的值
    value = ""
        // 失败后的原因
    reason = ""
    successCallback = []
    failCallback = []
    resolve = value => {
        if (this.status != PENDING) return //如果状态曾经被修改过直接返回
        this.status = FULFILED
        this.value = value
        while (this.successCallback.length) this.successCallback.shift()() //判断SUCUCESS中是否存在成功的回调函数
    }
    reject = reason => {
        if (this.status != PENDING) return //如果状态曾经被修改过直接返回
        this.status = REJECTED
        this.reason = reason
        while (this.failCallback.length) this.failCallback.shift()() //判断FAILED中是否存在失败的回调函数
    }
    static resolve(value) {
        if (value instanceof MyPromise) return value // 是promise对象直接返回
        return new MyPromise((resolve, reject) => {
            resolve(value)
        })
    }
    static all(array) {
        let arr = []
        return new MyPromise((resolve, reject) => {
            function addArr(i, item) {
                arr[i] = item
                if (arr.length = array.length) {
                    resolve(arr)
                }
            }
            for (let i = 0; i < array.length; i++) {
                if (array[i] instanceof MyPromise) { //array[i]为promise对象
                    array[i].then(value => addArr(i, value), reason => addArr(i, reason))
                } else {
                    addArr(i, array[i]) //array[i]为普通值
                }
            }
        })
    }
    then(successcallback, failedcallback) {
        successcallback = successcallback ? successcallback : value => value // 判断是否有传递成功的回调函数
        failedcallback = failedcallback ? failedcallback : reason => { throw reason } // 判断是否有传递失败的回调函数
        let promise2 = new MyPromise((resolve, reject) => {
            if (this.status == FULFILED) { //状态为成功执行下面语句
                setTimeout(() => {
                    try {
                        let x = successcallback(this.value)
                        resolvePromise(promise2, resolve, reject, x)
                    } catch (e) {
                        reject(e)
                    }
                }, 0);
            } else if (this.status == REJECTED) { //状态失败执行下面语句
                setTimeout(() => {
                    try {
                        let x = failedcallback(this.value)
                        resolvePromise(promise2, resolve, reject, x)
                    } catch (e) {
                        reject(e)
                    }
                }, 0);
            } else {
                //等待将成功的回调与失败的回调存储起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successcallback(this.value)
                            resolvePromise(promise2, resolve, reject, x)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0);
                })
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failedcallback(this.value)
                            resolvePromise(promise2, resolve, reject, x)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0);
                })
            }
            return promise2 //放回一个新的promise对象
        })


    }
    finally(callback) {
        return this.then((value) => {
            return MyPromise.resolve(callback()).then(() => value)
        }, (reason) => {
            return MyPromise.resolve(callback()).then(reason => { throw reason })
        })
    } catch (failcallback) {
        return this.then(undefined, failcallback)
    }
}

function resolvePromise(promise2, resolve, reject, x) {
    if (promise2 === x) { // 如果x与待返回的promise2为同一个对象就报错
        reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    } else if (x instanceof MyPromise) { //判断x是否为一个promise对象
        x.then(value => resolve(value), reason => reject(reason))
    } else {
        resolve(x) // x为普通值直接传入resolve中
    }
}